import 'dart:io';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/app_version.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';

///版本更新
class AppModel {
  ///获取App密钥
  ///baseUrl 传入输入的域名，通过密钥接口检查域名是否正确。
  ///isEnableLoad 是否显示网络进度条；true 显示，用户手动点击更新的；false 不显示，自动检查更新。
  static void checkUpdate(BuildContext context, bool isEnableLoad) {
    var url = Url.baseurl() + Url.sysappversion;
    var token = AppDataConfig.getToken();
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        //print('错误:\t$code\t$error');
      })
      ..onSuccess((result) {
        //http://test.bwg2017.com//UploadFile/AppVersion/202407161425597095.apk
        //{"Data":{"VersionCode":149,"VersionName":"1.4.9","ForceUpdate":true,"UpdateLog":"","DownloadUrl":"http://test.bwg2017.com//UploadFile/AppVersion/202407161425597095.apk"},"MsgCode":"100","MsgDetail":"获取成功"}
        //print('成功:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..addHeader('token', token)
      ..postASync<AppHttpResult<AppVersion, String>>(AppHttpResult()
            ..Data = AppVersion()
            ..t2 = "")
          ?.then((result) {
        if (result.isSuccessForData()) {
          AppVersion data = result!.Data!;
          var buildNumber = data?.VersionCode?.toString();
          _isUpdateVersionWithApp(buildNumber)?.then((value) {
            if (value) {
              //需要更新
              if (data.ForceUpdate) {
                //强制更新
                _showDialogWithUpdateForceUpdate(context, data);
              } else {
                //不强制，提示用户是否更新
                _showDialogWithUpdate(context, data);
              }
            } else {
              if (isEnableLoad) {
                //不需要更新;当前已是最新版本
                Toast.showSuccess(
                    AppStrings.of(context).latestVersion, context);
              }
            }
          });
        }
      });
  }
}

///判断APP是否需要更新
Future<bool> _isUpdateVersionWithApp(String? buildNumber) async {
  if (PlatformUtils.isAndroid()) {
    return AppUtils.isUpdateVersionWithApp(buildNumber);
  } else {
    return true;
  }
}

///显示更新弹窗
_showDialogWithUpdate(BuildContext context, AppVersion data) {
  var title = AppStrings.of(context).newVersion;
  var content = AppStrings.of(context).versionCode +
      ":" +
      data.VersionCode.toString() +
      "\n" +
      AppStrings.of(context).updateLog +
      ":" +
      data.UpdateLog;
  //不强制更新，有选择按钮
  AppDialog.showDialogWithAlert(context,
          title: title, content: content, isCenterContent: false)
      ?.then((value) {
    if (BoolUtils.isBool(value)) {
      _down(context, data.DownloadUrl);
    }
  });
}

///显示更新弹窗(强制更新)
_showDialogWithUpdateForceUpdate(BuildContext context, AppVersion data) {
  var title = AppStrings.of(context).newVersion; //发现新版本
  var content = title +
      "," +
      AppStrings.of(context).versionCode + //版本号
      ":" +
      data.VersionCode.toString() +
      "\n" +
      AppStrings.of(context).updateLog + //更新内容
      ":" +
      data.UpdateLog;
  //强制更新
  AppDialog.showDialogWithInfo(context, content: content)?.then((value) {
    _down(context, data.DownloadUrl);
  });
}

///下载
_down(BuildContext context, String url) {
  AppDialog.showDialogWithDown(context, url, response: (value) {
    // print("下载文件：${value.path}");
    // /data/user/0/cn.nbjianghua.bwg.app/cache/cache/filedown/202408011457189753.apk
    // 44.71331977844238MB
    // value.length()?.then((value) {
    //   print("文件大小：\t${FileUtils.getSizeForMB(value)}MB");
    // });
  });
}
